<?php 
namespace app\admin\controller;
class Auth{

	protected $view;

	function __construct() {
		$this -> view = new \mylib\View(\mylib\Config::get('view'));
	}

	public function login(){
		if (\Ebcms::isPost()) {
			$captcha = \mylib\Input::post('captcha');
			if (!$captcha || $captcha != \mylib\Session::get('admin_captcha')) {
				return $this -> error('验证码不正确！');
			}
			$account = \mylib\Input::post('account');
			$password = \mylib\Input::post('password');
			if (!$account || $account != \mylib\Config::get('admin.account')) {
				return $this -> error('账户或密码不正确！');
			}
			if (!$password || $password != \mylib\Config::get('admin.password')) {
				return $this -> error('账户或密码不正确！');
			}

			\mylib\Session::set('admin_login', 1);
			\mylib\Session::delete('admin_captcha');
			return \mylib\Response::redirect(\mylib\Route::buildUrl('/admin/index/index'));
		}else{
			return $this -> html($this -> fetch());
		}
	}

	public function logout(){
		\mylib\Session::delete('admin_login');
		return \mylib\Response::redirect(\mylib\Route::buildUrl('/admin/index/index'));
	}

	public function captcha(){
		$num = mt_rand(1, 50);
		$max = mt_rand($num, $num + 50);
		\mylib\Session::set('admin_captcha', $num);
		return \mylib\Response::image(\Captcha::create(($max-$num).'+?='.$max, 16));
	}

	protected function assign($data=[], $value=null){
		$this -> view -> assign($data, $value);
		return $this -> view;
	}

	protected function fetch($tpl=null, $data=[]){
		return $this -> view -> fetch($tpl, $data);
	}

	protected function html($html=''){
		return \mylib\Response::html($html);
	}

	protected function success($message='操作成功！', $url='', $data=[]){
		if (\Ebcms::isAjax()) {
			return \mylib\Response::json([
				'code'=>1,
				'message'=>$message,
				'url'=>$url,
				'data'=>$data,
			]);
		}else{
			return $this -> html($this -> assign([
				'code'=>1,
				'message'=>$message,
				'url'=>$url,
				'data'=>$data,
			]) -> fetch('/common/notice'));
		}
	}

	protected function error($message='操作失败！', $url='', $data=[]){
		if (\Ebcms::isAjax()) {
			return \mylib\Response::json([
				'code'=>0,
				'message'=>$message,
				'url'=>$url,
				'data'=>$data,
			]);
		}else{
			return $this -> html($this -> assign([
				'code'=>0,
				'message'=>$message,
				'url'=>$url,
				'data'=>$data,
			]) -> fetch('/common/notice'));
		}
	}
}